﻿using System.Linq;

namespace ComeSeeThis_MVC2.Models
{
    public class Security
    {
        // ReSharper disable InconsistentNaming
        //private readonly ComeSeeThisDBEntities context = new ComeSeeThisDBEntities();
        //private readonly AspNetStuffEntities aspnetContext = new AspNetStuffEntities();
        private static SecurityRepository securityRepository = new SecurityRepository();
        // ReSharper restore InconsistentNaming

        public static bool CanEditMotor(int motorId, string userName)
        {
            /* User is allowed to edit motor if
             *   - Is in appropriate role
             *          OR
             *   - Created the motor AND Motor has not been used in gearing recs
             */

            var motor = new MotorRepository().GetMotor(motorId);
            if (User.IsInRole(userName, "GearingAdmin,SiteAdmin")) return true;

            // Any Gearing recs?
            if (new GearingRecRepository().GetAllGearingRecsByMotorId(motorId).ToList().Count > 0) return false;

            return motor.SubmittedBy == userName;
        }

        public static bool CanEditCompany(int companyId, string userName)
        {
            return User.IsInRole(userName, "GearingAdmin,SiteAdmin");
        }

        public static bool UserCanPerformOperation(string userName, string operationCode)
        {
            var user = securityRepository.GetUser(userName);
            operationCode = operationCode.ToUpper();
            return SecurityRepository.UserCanPerformOperation(user.UserId, operationCode);
        }

        public static void AddUserToRole(string userName, string roleName)
        {
            var user = securityRepository.GetUser(userName);
            var role = securityRepository.GetRole(roleName);

            role.aspnet_Users.Add(user);
            securityRepository.Save();
        }


    }
}